import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

interface goods {
  goodsid: number;
  categoryid: number;
  goodsname: string;
  goodsimg: string;
  goodsprice: number;
  promotiontype: number;
  goodsstatus: number;
  goodsstock: number;
  goodsdetails: string;
}
interface category {
  categoryid: number;
  parentid: number;
  categoryname: string;
  level: number;
}
interface user{
  userid:number,
  usercode:string,
  username:string,
  email:string,
  sex:number,
  birthday:string,
  phoneno:number,
  header:string,
  type:number,
  status:number,
}
const store = createStore({
  state: {
    userInfo:<user>{},
    recently: <goods[]>[],
    category:<category>{}
  },
  mutations: {
    updateUserInfo(state, user: user) {
      state.userInfo=user;
    },
    updateRecently(state, goods: goods) {
      let index = state.recently.findIndex(
        (item) => item.goodsid == goods.goodsid
      );
      if (index < 0) {
        state.recently.push(goods);
      }
      if (state.recently.length > 2) {
        state.recently.shift();
      }
    },
    updateCategory(state, category: category) {
      state.category=category;
    },
  },
  actions: {
    updateUserInfo(context,user:user){
      context.commit("updateUserInfo", user)
    },
    updateRecently(context, goods: goods) {
      context.commit("updateRecently", goods);
    },
    updateCategory(context, category: category) {
      context.commit("updateCategory", category);
    },
  },
  getters: {
    getUserInfo(state) {
      return state.userInfo;
    },
    getRecently(state) {
      return state.recently;
    },
    getCategory(state) {
      return state.category;
    },
  },
  modules: {},
  plugins: [createPersistedState()],
});
export default store;
